package android.money.db;

import java.io.FileNotFoundException;
import java.util.Date;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.money.data.Transaction;
import android.util.Log;

public class TransactionManager {
	private SQLiteDatabase mDb;

	private Context ctx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DBInfo.DATABASE_NAME, null, DBInfo.DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DBInfo.TABLE_TRANSACTION_CREATE);
			db.execSQL(DBInfo.TABLE_ACCOUNT_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w("TransactionManager", "Upgrading database from version "
					+ oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS " + DBInfo.TABLE_ACCOUNT_NAME);
			db.execSQL("DROP TABLE IF EXISTS " + DBInfo.TABLE_TRANSACTION_NAME);
			onCreate(db);
		}
	}

	public TransactionManager(Context ctx) {
		this.ctx = ctx;
	}

	public TransactionManager open() {
		mDb = new DatabaseHelper(ctx).getWritableDatabase();
		return this;
	}

	public boolean addTransaction(Transaction transaction) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(DBInfo.trans_acc_id, transaction.getAccount_id());
		initialValues.put(DBInfo.trans_reader, transaction.getReader());
		initialValues.put(DBInfo.trans_amount, transaction.getAmount());
		initialValues.put(DBInfo.trans_unit, transaction.getUnit());
		initialValues.put(DBInfo.trans_time, new Date().getTime());
		if (mDb.insert(DBInfo.TABLE_TRANSACTION_NAME, null, initialValues) < 0)
			return false;
		return true;
	}

	public Cursor fetchTransactions(long from, long to, int accountId) {
		// Log.w("TRANS",
		// DBInfo.trans_time+" <= "+to+" AND "+DBInfo.trans_time+" >= "
		// +from+" AND "+DBInfo.trans_acc_id+" = "+accountId);
		if (accountId >= 0)
			return mDb.query(DBInfo.TABLE_TRANSACTION_NAME, new String[] {
					DBInfo.trans_id, DBInfo.trans_acc_id, DBInfo.trans_amount,
					DBInfo.trans_unit, DBInfo.trans_time }, DBInfo.trans_time
					+ " <= " + to + " AND " + DBInfo.trans_time + " >= " + from
					+ " AND " + DBInfo.trans_acc_id + " = " + accountId, null,
					null, null, null);
		return mDb.query(DBInfo.TABLE_TRANSACTION_NAME, new String[] {
				DBInfo.trans_id, DBInfo.trans_acc_id, DBInfo.trans_amount,
				DBInfo.trans_unit, DBInfo.trans_time }, DBInfo.trans_time
				+ " <= " + to + " AND " + DBInfo.trans_time + " >= " + from,
				null, null, null, null);

	}

	public void close() {
		mDb.close();
	}
}
